#include "LibrarySystem.h"
#include <iostream>
#include <sstream>

LibrarySystem::LibrarySystem()
    : bookHead(nullptr), readerHead(nullptr), recordHead(nullptr), recordCounter(1) {
    loadAllData();
}

LibrarySystem::~LibrarySystem() {
    saveAllData();

    // 释放链表内存
    Node<Book>* bookCurrent = bookHead;
    while (bookCurrent) {
        Node<Book>* next = bookCurrent->next;
        delete bookCurrent;
        bookCurrent = next;
    }

    Node<Reader>* readerCurrent = readerHead;
    while (readerCurrent) {
        Node<Reader>* next = readerCurrent->next;
        delete readerCurrent;
        readerCurrent = next;
    }

    Node<BorrowRecord>* recordCurrent = recordHead;
    while (recordCurrent) {
        Node<BorrowRecord>* next = recordCurrent->next;
        delete recordCurrent;
        recordCurrent = next;
    }
}

// 文件操作实现
void LibrarySystem::loadBooksFromFile() {
    ifstream file("books.dat");
    if (!file) {
        return;
    }
    if (file.peek() == ifstream::traits_type::eof()) {
        cout << "数据文件为空或已损坏，将重新创建。" << endl;
        file.close();
        return;
    }
    string line;
    while (getline(file, line)) {
        if (!line.empty()) {
            Book book = Book::fromString(line);
            addNode(bookHead, book);
        }
    }
    file.close();
}

void LibrarySystem::loadReadersFromFile() {
    ifstream file("readers.txt");
    if (!file) {
        cout << "未找到读者数据文件，将创建新文件。" << endl;
        return;
    }

    string line;
    while (getline(file, line)) {
        if (!line.empty()) {
            Reader reader = Reader::fromString(line);
            addNode(readerHead, reader);
        }
    }
    file.close();
}

void LibrarySystem::loadRecordsFromFile() {
    ifstream file("records.txt");
    if (!file) {
        cout << "未找到借阅记录数据文件，将创建新文件。" << endl;
        return;
    }

    string line;
    while (getline(file, line)) {
        if (!line.empty()) {
            BorrowRecord record = BorrowRecord::fromString(line);
            addNode(recordHead, record);
            if (record.getRecordId() >= recordCounter) {
                recordCounter = record.getRecordId() + 1;
            }
        }
    }
    file.close();
}

void LibrarySystem::saveBooksToFile() {
    ofstream file("books.txt");
    if (!file) {
        cout << "无法保存图书数据！" << endl;
        return;
    }

    Node<Book>* current = bookHead;
    while (current) {
        file << current->data.toString() << endl;
        current = current->next;
    }
    file.close();
}

void LibrarySystem::saveReadersToFile() {
    ofstream file("readers.txt");
    if (!file) {
        cout << "无法保存读者数据！" << endl;
        return;
    }

    Node<Reader>* current = readerHead;
    while (current) {
        file << current->data.toString() << endl;
        current = current->next;
    }
    file.close();
}

void LibrarySystem::saveRecordsToFile() {
    ofstream file("records.txt");
    if (!file) {
        cout << "无法保存借阅记录数据！" << endl;
        return;
    }

    Node<BorrowRecord>* current = recordHead;
    while (current) {
        file << current->data.toString() << endl;
        current = current->next;
    }
    file.close();
}

// ========== 图书管理功能 ==========
void LibrarySystem::addBook() {
    string bookId, title, author, publisher, category;
    int totalCount;

    cout << "请输入图书信息:" << endl;
    cout << "书号(格式B001): "; cin >> bookId;

    // 书号格式校验
    if (bookId.length() != 4 || bookId[0] != 'B' ||
        !isdigit(bookId[1]) || !isdigit(bookId[2]) || !isdigit(bookId[3])) {
        cout << "错误：书号格式不正确！应为B001格式" << endl;
        return;
    }

    cout << "书名: "; cin.ignore(); getline(cin, title);
    cout << "作者: "; getline(cin, author);
    cout << "出版社: "; getline(cin, publisher);
    cout << "分类: "; getline(cin, category);
    cout << "总藏书量: "; cin >> totalCount;

    Book newBook(bookId, title, author, publisher, category, totalCount);
    addNode(bookHead, newBook);
    cout << "图书添加成功！" << endl;
}

void LibrarySystem::deleteBook() {
    string bookId;
    cout << "请输入要删除的图书书号: "; cin >> bookId;

    Book* book = findNode(bookHead, bookId);
    if (!book) {
        cout << "错误：图书不存在！" << endl;
        return;
    }

    // 检查是否有未归还的借阅记录
    Node<BorrowRecord>* current = recordHead;
    while (current) {
        if (current->data.getBookId() == bookId && !current->data.getIsReturned()) {
            cout << "错误：该图书有未归还的借阅记录，无法删除！" << endl;
            return;
        }
        current = current->next;
    }

    if (removeNode(bookHead, *book)) {
        cout << "图书删除成功！" << endl;
    }
    else {
        cout << "图书删除失败！" << endl;
    }
}

void LibrarySystem::modifyBook() {
    string bookId;
    cout << "请输入要修改的图书书号: "; cin >> bookId;

    Book* book = findNode(bookHead, bookId);
    if (!book) {
        cout << "错误：图书不存在！" << endl;
        return;
    }

    cout << "当前图书信息：" << endl;
    book->displayInfo();

    string title, author, publisher, category;
    int totalCount;

    cout << "请输入新的图书信息（直接回车保持原值）：" << endl;
    cout << "书名: "; cin.ignore(); getline(cin, title);
    if (!title.empty()) book->setTitle(title);

    cout << "作者: "; getline(cin, author);
    if (!author.empty()) book->setAuthor(author);

    cout << "出版社: "; getline(cin, publisher);
    if (!publisher.empty()) book->setPublisher(publisher);

    cout << "分类: "; getline(cin, category);
    if (!category.empty()) book->setCategory(category);

    cout << "总藏书量: ";
    string countStr;
    getline(cin, countStr);
    if (!countStr.empty()) {
        totalCount = stoi(countStr);
        book->setTotalCount(totalCount);
    }

    cout << "图书信息修改成功！" << endl;
}

void LibrarySystem::searchBooks() {
    string keyword;
    cout << "请输入查询关键词: ";
    cin.ignore();
    getline(cin, keyword);

    Node<Book>* current = bookHead;
    bool found = false;

    cout << "查询结果：" << endl;
    while (current) {
        if (current->data.getBookId().find(keyword) != string::npos ||
            current->data.getTitle().find(keyword) != string::npos ||
            current->data.getAuthor().find(keyword) != string::npos ||
            current->data.getCategory().find(keyword) != string::npos) {
            current->data.displayInfo();
            found = true;
        }
        current = current->next;
    }

    if (!found) {
        cout << "未找到符合条件的图书！" << endl;
    }
}

void LibrarySystem::displayAllBooks() {
    vector<Book> books = getAllNodes(bookHead);
    if (books.empty()) {
        cout << "系统中暂无图书！" << endl;
        return;
    }

    cout << "所有图书信息：" << endl;
    for (const auto& book : books) {
        book.displayInfo();
    }
    cout << "共 " << books.size() << " 本图书" << endl;
}

// ========== 读者管理功能 ==========
void LibrarySystem::addReader() {
    string readerId, name, gender, type, phone;

    cout << "请输入读者信息:" << endl;
    cout << "读者号: "; cin >> readerId;
    if (readerId.length() != 4 || readerId[0] != 'R' ||
        !isdigit(readerId[1]) || !isdigit(readerId[2]) || !isdigit(readerId[3])) {
        cout << "错误：读者号格式不正确！应为R001格式" << endl;
        return;
    }
    // 检查读者号是否唯一
    if (findNode(readerHead, readerId)) {
        cout << "错误：读者号已存在！" << endl;
        return;
    }

    cout << "姓名: "; cin.ignore(); getline(cin, name);
    cout << "性别: "; getline(cin, gender);
    cout << "类型: "; getline(cin, type);
    cout << "联系方式: "; getline(cin, phone);

    Reader newReader(readerId, name, gender, type, phone);
    addNode(readerHead, newReader);
    cout << "读者添加成功！" << endl;
}

void LibrarySystem::deleteReader() {
    string readerId;
    cout << "请输入要删除的读者号: "; cin >> readerId;

    Reader* reader = findNode(readerHead, readerId);
    if (!reader) {
        cout << "错误：读者不存在！" << endl;
        return;
    }

    // 检查是否有未归还的借阅记录
    Node<BorrowRecord>* current = recordHead;
    while (current) {
        if (current->data.getReaderId() == readerId && !current->data.getIsReturned()) {
            cout << "错误：该读者有未归还的借阅记录，无法删除！" << endl;
            return;
        }
        current = current->next;
    }

    if (removeNode(readerHead, *reader)) {
        cout << "读者删除成功！" << endl;
    }
    else {
        cout << "读者删除失败！" << endl;
    }
}

void LibrarySystem::modifyReader() {
    string readerId;
    cout << "请输入要修改的读者号: "; cin >> readerId;

    Reader* reader = findNode(readerHead, readerId);
    if (!reader) {
        cout << "错误：读者不存在！" << endl;
        return;
    }

    cout << "当前读者信息：" << endl;
    reader->displayInfo();

    string name, gender, type, phone;

    cout << "请输入新的读者信息（直接回车保持原值）：" << endl;
    cout << "姓名: "; cin.ignore(); getline(cin, name);
    if (!name.empty()) reader->setName(name);

    cout << "性别: "; getline(cin, gender);
    if (!gender.empty()) reader->setGender(gender);

    cout << "类型: "; getline(cin, type);
    if (!type.empty()) reader->setType(type);

    cout << "联系方式: "; getline(cin, phone);
    if (!phone.empty()) reader->setPhone(phone);

    cout << "读者信息修改成功！" << endl;
}

void LibrarySystem::searchReaders() {
    string keyword;
    cout << "请输入查询关键词: ";
    cin.ignore();
    getline(cin, keyword);

    Node<Reader>* current = readerHead;
    bool found = false;

    cout << "查询结果：" << endl;
    while (current) {
        if (current->data.getReaderId().find(keyword) != string::npos ||
            current->data.getName().find(keyword) != string::npos) {
            current->data.displayInfo();
            found = true;
        }
        current = current->next;
    }

    if (!found) {
        cout << "未找到符合条件的读者！" << endl;
    }
}

void LibrarySystem::manageBlacklist() {
    int choice;
    cout << "1. 加入黑名单" << endl;
    cout << "2. 移出黑名单" << endl;
    cout << "请选择操作: "; cin >> choice;

    string readerId;
    cout << "请输入读者号: "; cin >> readerId;

    Reader* reader = findNode(readerHead, readerId);
    if (!reader) {
        cout << "错误：读者不存在！" << endl;
        return;
    }

    if (choice == 1) {
        reader->setIsBlacklisted(true);
        cout << "读者已加入黑名单！" << endl;
    }
    else if (choice == 2) {
        reader->setIsBlacklisted(false);
        cout << "读者已移出黑名单！" << endl;
    }
    else {
        cout << "无效选择！" << endl;
    }
}

void LibrarySystem::displayAllReaders() {
    vector<Reader> readers = getAllNodes(readerHead);
    if (readers.empty()) {
        cout << "系统中暂无读者！" << endl;
        return;
    }

    cout << "所有读者信息：" << endl;
    for (const auto& reader : readers) {
        reader.displayInfo();
    }
    cout << "共 " << readers.size() << " 位读者" << endl;
}

// ========== 借阅管理功能 ==========
void LibrarySystem::borrowBook() {
    string bookId, readerId;
    cout << "请输入借阅信息:" << endl;
    cout << "读者号: "; cin >> readerId;
    cout << "图书号: "; cin >> bookId;

    Reader* reader = findNode(readerHead, readerId);
    Book* book = findNode(bookHead, bookId);

    if (!reader) {
        cout << "错误：读者不存在！" << endl;
        return;
    }
    if (!book) {
        cout << "错误：图书不存在！" << endl;
        return;
    }
    if (reader->getIsBlacklisted()) {
        cout << "错误：读者在黑名单中，无法借阅！" << endl;
        return;
    }
    if (book->getAvailableCount() <= 0) {
        cout << "错误：图书已全部借出！" << endl;
        return;
    }
    if (reader->getCurrentBorrowCount() >= reader->getMaxBorrowCount()) {
        cout << "错误：读者借阅数量已达上限！" << endl;
        return;
    }

    // 创建借阅记录
    time_t now = time(nullptr);
    time_t dueDate = now + 30 * 24 * 60 * 60; // 30天后到期

    BorrowRecord newRecord(recordCounter++, bookId, readerId, now, dueDate);
    addNode(recordHead, newRecord);

    // 更新图书和读者信息
    book->setAvailableCount(book->getAvailableCount() - 1);
    reader->setCurrentBorrowCount(reader->getCurrentBorrowCount() + 1);

    cout << "借阅成功！记录号: " << newRecord.getRecordId() << endl;
    cout << "应还日期: " << BorrowRecord::timeToString(dueDate) << endl;
}

void LibrarySystem::returnBook() {
    string bookId, readerId;
    cout << "请输入归还信息:" << endl;
    cout << "读者号: "; cin >> readerId;
    cout << "图书号: "; cin >> bookId;

    // 查找未归还的记录
    Node<BorrowRecord>* current = recordHead;
    BorrowRecord* record = nullptr;

    while (current) {
        if (current->data.getBookId() == bookId &&
            current->data.getReaderId() == readerId &&
            !current->data.getIsReturned()) {
            record = &(current->data);
            break;
        }
        current = current->next;
    }

    if (!record) {
        cout << "错误：未找到对应的借阅记录！" << endl;
        return;
    }

    // 更新记录
    time_t now = time(nullptr);
    record->setReturnDate(now);
    record->setIsReturned(true);

    double fine = record->calculateFine();
    if (fine > 0) {
        record->setFineAmount(fine);
        cout << "产生逾期罚款: " << fine << "元" << endl;
    }

    // 更新图书和读者信息
    Book* book = findNode(bookHead, bookId);
    Reader* reader = findNode(readerHead, readerId);

    if (book) book->setAvailableCount(book->getAvailableCount() + 1);
    if (reader) reader->setCurrentBorrowCount(reader->getCurrentBorrowCount() - 1);

    cout << "归还成功！" << endl;
}

void LibrarySystem::displayAllRecords() {
    vector<BorrowRecord> records = getAllNodes(recordHead);
    if (records.empty()) {
        cout << "系统中暂无借阅记录！" << endl;
        return;
    }

    cout << "所有借阅记录：" << endl;
    for (const auto& record : records) {
        record.displayInfo();
    }
    cout << "共 " << records.size() << " 条借阅记录" << endl;
}

void LibrarySystem::displayOverdueRecords() {
    Node<BorrowRecord>* current = recordHead;
    bool found = false;

    cout << "逾期记录：" << endl;
    while (current) {
        if (!current->data.getIsReturned() && current->data.getOverdueDays() > 0) {
            current->data.displayInfo();
            found = true;
        }
        current = current->next;
    }

    if (!found) {
        cout << "暂无逾期记录！" << endl;
    }
}

// ========== 查询功能 ==========
void LibrarySystem::bookQuery() {
    searchBooks(); // 复用搜索功能
}

void LibrarySystem::readerQuery() {
    searchReaders(); // 复用搜索功能
}

void LibrarySystem::readerRecordQuery() {
    string readerId;
    cout << "请输入读者号: "; cin >> readerId;

    Node<BorrowRecord>* current = recordHead;
    bool found = false;

    cout << "读者 " << readerId << " 的借阅记录：" << endl;
    while (current) {
        if (current->data.getReaderId() == readerId) {
            current->data.displayInfo();
            found = true;
        }
        current = current->next;
    }

    if (!found) {
        cout << "该读者暂无借阅记录！" << endl;
    }
}

// ========== 系统功能 ==========
void LibrarySystem::saveAllData() {
    saveBooksToFile();
    saveReadersToFile();
    saveRecordsToFile();
    cout << "所有数据已保存！" << endl;
}

void LibrarySystem::loadAllData() {
    loadBooksFromFile();
    loadReadersFromFile();
    loadRecordsFromFile();
}